package com.czl.module_base.observer;

import androidx.annotation.NonNull;

import com.czl.base.util.ToastHelper;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.view.IView;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author by xubin,
 * @date on 2022/1/24.
 * PS: Not easy to write code, please indicate.
 */
public abstract class AbsHandleSubscriber<T> implements Observer<T> {

    private IView mView;

    private boolean useCode;

    public AbsHandleSubscriber() {
    }

    public AbsHandleSubscriber(boolean useCode) {
        this.useCode = useCode;
    }

    public AbsHandleSubscriber(IView view) {
        mView = view;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull T t) {
        if (t instanceof HttpResponse) {
            if (useCode) {
                next(t, ((HttpResponse<?>) t).isSuccessCode());
            } else {
                next(t, ((HttpResponse<?>) t).isSuccess());
            }
        }
    }

    private void next(@NonNull T t, boolean success) {
        if (success) {
            if (mView != null) {
                mView.showLoadSuccess();
            }
            onSuccess(t);
        } else {
            onFailed(((HttpResponse<?>) t).getMsg());
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        if (mView == null) {
            onFailed(e.getMessage());
        } else {
            mView.showError(e.getMessage());
        }
    }

    @Override
    public void onComplete() {

    }

    /**
     * 加载成功
     *
     * @param t t
     */
    public abstract void onSuccess(T t);

    public void onFailed(String msg) {
        if (mView != null) {
            mView.showError(msg);
        }
        ToastHelper.INSTANCE.showErrorToast(msg);
    }

}
